<template>
  <div class="app-container">
    <el-form
      :model="searchParams"
      ref="searchForm"
      :inline="true"
      v-show="showSearch"
      label-position="left"
      label-width="80px"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="模板名称" prop="templateId">
            <el-select
              v-model="searchParams.templateId"
              placeholder="请选择模板名称"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="dict in templateIdOptions"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="字段名称" prop="fieldName">
            <el-input
              v-model="searchParams.fieldName"
              placeholder="请输入字段名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="字段类型" prop="fieldType">
            <el-select
              v-model="searchParams.fieldType"
              placeholder="请选择字段类型"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="dict in fieldTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-circle-plus-outline"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['template:management:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['template:management:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['template:management:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['template:management:export']"
          >导出</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList()"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="templateFieldList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板字段ID" align="center" prop="id" />
      <el-table-column label="关联模板ID" align="center" prop="templateId" />
      <el-table-column label="字段名称" align="center" prop="fieldName" />
      <el-table-column label="字段分类" align="center" prop="fieldType">
        <template slot-scope="scope">
          <span v-if="scope.row.fieldType === 1">字符串</span>
          <span v-if="scope.row.fieldType === 2">字符串数组</span>
          <span v-if="!scope.row.fieldType">--</span>
        </template>
      </el-table-column>
      <el-table-column
        label="字段默认值"
        align="center"
        prop="defaultFieldValue"
      />
      <el-table-column label="版本" align="center" prop="version" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updateBy" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['template:management:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['template:management:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="searchParams.pageNum"
      :limit.sync="searchParams.pageSize"
      @pagination="getList()"
    />

    <!-- 添加或修改字段资源对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="字段名称" prop="fieldName">
          <el-input v-model="form.fieldName" placeholder="请输入字段名称" />
        </el-form-item>

        <el-form-item label="字段分类" prop="fieldType">
          <el-select
            v-model="form.fieldType"
            placeholder="请选择字段分类"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in fieldTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="字段默认值" prop="defaultFieldValue">
          <el-input
            v-model="form.defaultFieldValue"
            placeholder="请输入字段默认值"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryTemplateFieldList,
  queryTemplateFieldListDetail,
  delTemplateField,
  addTemplateField,
  updateTemplateField,
  exportTemplateField,
  queryTemplateListDetail,
  queryTemplateList
} from '@/api/template/field'

export default {
  name: 'templateFieldManagement',
  components: {},
  data() {
    return {
      fieldTypeOptions: [],
      templateIdOptions: [],
      rowId: this.$route.params && this.$route.params.rowId,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字段资源表格数据
      templateFieldList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      fileList: [],
      // 查询参数
      searchParams: {
        pageNum: 1,
        pageSize: 10,
        templateId: null,
        fieldName: null,
        fieldType: null
      },
      searchTemplateNameParams: {
        pageNum: 1,
        pageSize: 9999
      },
      // 表单参数
      form: {
        id: null,
        fieldName: null,
        fieldType: null,
        templateId: null,
        defaultFieldValue: null
      },
      // 表单校验
      rules: {}
    }
  },
  created() {
    const dictId = this.$route.params && this.$route.params.rowId
    this.getTemplateName(dictId)
    this.getTemplateNameList()
    this.getDicts('cms_template_field_type').then(response => {
      this.fieldTypeOptions = response.data
    })
  },
  methods: {
    // 模板详细接口查详情数据
    getTemplateName(dictId) {
      queryTemplateListDetail(dictId).then(response => {
        this.searchParams.templateId = response.data.id
        this.getList()
      })
    },

    // 获取options数据
    getTemplateNameList() {
      queryTemplateList().then(response => {
        this.templateIdOptions = response.rows
      })
    },

    //  查询字段资源列表
    getList() {
      this.loading = true
      queryTemplateFieldList(this.searchParams).then(response => {
        this.templateFieldList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        templateId: undefined,
        defaultFieldValue: undefined,
        fieldName: undefined,
        fieldType: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.searchParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('searchForm')
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 导出按钮操作 */
    handleExport() {
      const searchParams = this.searchParams
      this.$confirm('是否确认导出所有角色数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true
          return exportTemplateField(searchParams)
        })
        .then(response => {
          this.download(response.msg)
          this.exportLoading = false
        })
        .catch(() => {})
    },

    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加字段模板'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true
      this.reset()
      const id = row.id || this.ids
      queryTemplateFieldListDetail(id).then(response => {
        // response.data.fieldType = response.data.fieldType + ''
        this.loading = false
        this.form = response.data
        this.open = true
        this.title = '修改字段模板'
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.id != null) {
            updateTemplateField(this.form).then(response => {
              this.buttonLoading = false
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            this.form.templateId = this.rowId
            addTemplateField(this.form).then(response => {
              this.buttonLoading = false
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm(
        '是否确认删除字段资源编号为"' + ids + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.loading = true
          return delTemplateField(ids)
        })
        .then(() => {
          this.loading = false
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(() => {})
    }
  }
}
</script>
<style scoped lang="scss">
</style>